<template>
  <div class="login_container">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
    >
      <h3>学习管理系统</h3>
      <el-form-item label="账号" prop="username">
        <el-input v-model="ruleForm.username" autocomplete="off" @keydown.enter="submitForm(ruleFormRef)"/>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="ruleForm.password"
          type="password"
          autocomplete="off"
          @keydown.enter="submitForm(ruleFormRef)"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import Cookie from "js-cookie";
import axios from "axios";
import { ElMessage } from 'element-plus'

const router = useRouter();
const ruleFormRef = ref();
const validatePass = (rule, value, callback) => {
  if (value === "") {
    callback(new Error("清输入密码"));
  } else {
    callback();
  }
};

const ruleForm = reactive({
  username: "",
  password: "",
});

const rules = {
  username: [{ required: true, trigger: "blur", message: "请输入用户名" }],
  password: [
    {
      required: true,
      validator: validatePass,
      trigger: "blur",
      message: "请输入密码",
    },
  ],
};
const submitLogin = async () => {
  const { data } = await axios.post("/api/login", ruleForm, {
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
  });
  if (data.code === 200) {
    Cookie.set("token", data.token);
    Cookie.set("id", data.id);
    Cookie.set("user", data.user);
    ElMessage.success('登录成功')
    router.push("/");
  } else {
    ElMessage.error(data.message)
  }
};
const submitForm = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      submitLogin();
    }
  });
};
</script>

<style lang="less">
.login_container {
  width: 100vw;
  height: 100vh;
  background: #545c64;
  position: relative;
  h3 {
    margin-bottom: 10px;
    text-align: center;
  }
}
.el-form {
  width: 500px;
  height: 240px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  background: #fff;
  padding: 30px;
}
</style>
